package stu.officedrunker.applications.common.scheduling;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.scheduling.quartz.QuartzJobBean;

import stu.officedrunker.applications.lucky.service.LuckyService;
import stu.officedrunker.applications.lucky.vo.LuckyRequestVO;

import com.rntsappstore.base.util.date.TimeConvert;

@Configurable
public class LuckyScheduler extends QuartzJobBean {
	
	// 동작 기본설정
	private static Object syncObj = new Object();
	private static boolean isWork = false;

	// 실제 동작시킬지 에 대한 결정. (true = 실행)
	private boolean enabled = true;
	
	@Autowired
	private LuckyService luckyService;

	public void setLuckyService(LuckyService luckyService) {
		this.luckyService = luckyService;
	}

	@Override
	protected void executeInternal(JobExecutionContext arg0) throws JobExecutionException {
		// 실제 scheduling 작업
		
		if (!enabled || isWork)
			return;
		
		synchronized (syncObj) {
			if (isWork)
				return;
			isWork = true;
		}
		
		try {
			
			// 어제 날자 뽑기
			Date today  = new Date();
			Date selDate = new Date();
			SimpleDateFormat simple = new SimpleDateFormat("yyyy-MM-dd");
			selDate.setTime( today.getTime() + (1000 * 60 * 60 * 24)*  -1 ); // 제일 끝 변수 가 -1 = 어제, 0 = 오늘, 1 = 내일
			
			// 오늘 날자
			//String preDate = "2013-04-23"; //2012-12-11
			String preDate = simple.format(selDate);
			
			// 현재 날자
			// 오늘 날자를 뽑아서 YYYY-MM-DD 형식으로 만들고
			//svo.setSystemDate("2013-04-24"); //2012-12-12
			String systemDate = TimeConvert.systemTime().substring(0, 11);
			
			System.out.println("어제 날자 : " + preDate);
			System.out.println("오늘 날자 : " + systemDate);
			
			LuckyRequestVO luckyVO = new LuckyRequestVO();
			
			luckyVO.setUserId(preDate);
			luckyVO.setUserNm(systemDate);
			
			luckyService.getTest(luckyVO);
			
			isWork = false;
		} catch (Exception e) {
			isWork = false;
			throw (JobExecutionException) e;
		}
	} // End of Schediler
	
	
}